﻿using System;
using AutoMapper;
using Enferno.Public.InversionOfControl;
using Microsoft.Practices.Unity;
using Enferno.Public.Web.Components.Server.ViewModels;
using Enferno.Public.Web.Models;
using Enferno.Public.Web.Repositories;
using Enferno.StormApiClient.Customers;
using Enferno.Web.StormUtils;

namespace Enferno.Public.Web.Components.Server.Managers
{
    public class CustomerManager
    {
        private readonly IRepository _repository;

        public CustomerManager()
        {
            if (_repository == null)
                _repository = IoC.Container.Resolve<IRepository>();
        }

        [Obsolete("Use other ctor.")]
        public CustomerManager(ICustomerRepository repository) : this()
        {
        }

        public CustomerManager(IRepository repository)
        {
            _repository = repository;
        }

        public CustomerViewModel GetCustomerInformation(string socialSecurityNumber)
        {
            var customer = _repository.Customers.GetExternalAddress(socialSecurityNumber);
            var customerModel = Mapper.Map<Customer, CustomerModel>(customer);
            return Mapper.Map<CustomerModel, CustomerViewModel>(customerModel);
        }

        public CustomerViewModel Login(string userName, string password, bool remeberMe)
        {
            var customer = _repository.Customers.Login(userName, password);

            if (customer == null) return null; //we did not succeed to login. We have no idea why however...

            StormContext.LoginUser(userName, remeberMe);
            var customerModel = Mapper.Map<Customer, CustomerModel>(customer);
            return Mapper.Map<CustomerModel, CustomerViewModel>(customerModel);
        }

        public void Logout()
        {
            StormContext.LogoutUser();
        }
    }
}
